package com.chennan.book.api.rest.servicecontroller;

import java.io.*;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.chennan.book.api.rest.servicecontroller.dto.BookDTO;
import com.chennan.book.domain.model.*;
import com.chennan.book.domain.service.BookService;
import com.chennan.book.domain.service.BookServiceInteface;
import com.chennan.common.util.ExcelPoiUtil;
import com.chennan.redis.domain.service.RedisServiceComplete;
import com.chennan.springaop.domain.annotation.PreventRepeatedSubmit;
import io.swagger.models.auth.In;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import com.chennan.book.domain.repository.BookMapper;
import org.springframework.web.multipart.MultipartFile;
import uk.co.jemos.podam.api.PodamFactory;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/book")
public class BookController {
	
	@Autowired
	private BookMapper book;

	@Autowired
	private BookServiceInteface bookService;

	@Resource
	private PodamFactory factory;

	private Integer count = 0 ;

	@GetMapping("/mybaits-update/{no}")
	public void updateMybatisCacheNot(@PathVariable("no") String no){
		bookService.updateMybatisCacheHave(no);
	}

	@GetMapping("/mybaits-cache-not/{no}")
	public void testMybatisCacheNot(@PathVariable("no") String no){
		bookService.testMybatisCacheNot(no);
	}
	@GetMapping("/mybaits-cache-have/{no}")
	public void testMybatisCacheHave(@PathVariable("no") String no){
		bookService.testMybatisCacheHave(no);
	}

	@GetMapping("/get-submit")
	public String getSubmit(){
		List<String> list = new ArrayList<>();
		return bookService.getSubmit(list);
	}


	@PostMapping("/get-allbook")
//	@PreventRepeatedSubmit(lockTime=10)
	public List<Book> getAllBook() {
		BookTitle title = new BookTitle();
		title.setBizType(1);
		title.setTitle("111");

		BookType type = new BookType();
		type.setType(1);
		type.setBizType(2);
//		List<Book> bookeData1 = this.book.queryAllBook(title);
//		List<Book> bookeData2 = this.book.queryAllBook(type);
//		System.out.println(bookeData1);
//		System.out.println(bookeData2);
//		List<Book> bookeData = this.book.queryAllBook(condition);
//		Book book = new Book();
//		book.setTitle("这是个默认测试的书1");
//		bookeData.add(book);
//		bookeData.add(book);
		return null;
	}

	@PostMapping("/update-book")
	@Transactional
	public Integer updateBook(@RequestBody BookDTO bookDTO){
		Book bookModel = new Book();
		BeanUtils.copyProperties(bookDTO,bookModel);
		book.updateBook(bookModel);
		return 1;
	}

	@PostMapping("/create-book")
	@Transactional
	public Integer createBook(@RequestBody BookDTO bookDTO){
		Book bookModel = new Book();
		BeanUtils.copyProperties(bookDTO,bookModel);
		book.insertBook(bookModel);
		System.out.println(JSON.toJSONString(bookModel));
		return 1;
	}

	@GetMapping("test-create-book/{num}")
	public String TestCrateBook(@PathVariable("num") Integer num){
		if (num==null) {
			return "请输入正确的参数";
		}
		for (int i = 0; i < num; i++) {
			BookDTO bookDTO = new BookDTO();
			bookDTO.setCommentnum(i).
					setLink("wwww.www.www").
					setPrice(i*1.2).
					setTitle("这是什么书").
					setType(num%3);
			createBook(bookDTO);
		}
		return "生成成功！";
	}

	@PostMapping("/update/books")
	public Integer updateBooks(@RequestBody List<Book> books){
		return this.book.updateBooks(books);
	}

	@GetMapping("/testRetryable")
	public String testRetryable(){
		count++;
		bookService.testRetryable();

		return "测试"+count;
	}

	@GetMapping("/testMysqlIn")
	public String testMysqlIn(){
		List<Long> test = new ArrayList<>();
		for (int i = 0; i < 100000; i++) {
			test.add(Long.valueOf(i+""));
		}
		List<Integer> version =book.queryOrderVersion(test);
		return version.toString();
	}

	@GetMapping("/bulkInsert/{num}")
	@Transactional
	public String bulkInsert(@PathVariable("num") Integer num){
		List<SupplierInvoiceReceivableBill> list = new ArrayList<>(num);
		for (int i = 0; i < num; i++) {
			SupplierInvoiceReceivableBill accountReceiveableItem = factory.manufacturePojo(SupplierInvoiceReceivableBill.class);
			accountReceiveableItem.setCurrentTaxRate(new BigDecimal("1"));
			accountReceiveableItem.setTaxRate(new BigDecimal("1"));
			accountReceiveableItem.setUnit("1");
			list.add(accountReceiveableItem);
		}
		System.out.println("开始插入");
		long l = System.currentTimeMillis();
		Integer integer = book.batchSaveSupplierInvoiceReceivableBill(list);
		long l1 = System.currentTimeMillis();
		System.out.println("开始完成："+(l1-l));
		return "插入成功！";
	}

	@Autowired
	private RedisServiceComplete redisServiceComplete;
	/**
	 * redis 学习
	 */
	@GetMapping("study-redis")
	public String studyRedis(){
		redisServiceComplete.del("invoice-count");
		for (int i=300000;i<=1200000;i+=300000){
			redisServiceComplete.rpush("invoice-count",i);
		}
		return "1111";
	}
	@GetMapping("lpop-redis")
	public Long getList(){
		String lpop = redisServiceComplete.lpop("invoice-count");
		return Long.parseLong(lpop);
	}

	@GetMapping("delete-redis/{key}")
	public Long getList(@PathVariable("key") String key){
		redisServiceComplete.del(key);
		return 1L;
	}

	@GetMapping("excel/out")
	public void downExcel(HttpServletResponse response){
		List<ExcelExportTest> testList = new ArrayList<>();
		for (int i = 0; i < 10; i++) {
			ExcelExportTest excelExportTest = new ExcelExportTest();
			excelExportTest.setId(Long.valueOf(i+""));
			excelExportTest.setNumber(i+1);
			excelExportTest.setZicdl("计算机"+i);
			excelExportTest.setZicmc("资产名称"+i);
			testList.add(excelExportTest);
		}
		List<DataExportInfo> dataExportInfos = new ArrayList<>();
		DataExportInfo dataExportInfo = new DataExportInfo();
		dataExportInfo.setData(testList);
		dataExportInfo.setEntity(ExcelExportTest.class);
		dataExportInfo.setSheetName("资产名称导出");
		dataExportInfo.setTitleName("资产分类导出展示列表");
		dataExportInfos.add(dataExportInfo);
		List<Map<String, Object>> exportData = getExportData(dataExportInfos);
		ExcelPoiUtil.exportExcel(exportData,"导出测试" + LocalDate.now() + ".xls",response);
	}

	/**
	 * 组装导出数据
	 *
	 * @param exportInfoList
	 * @return
	 */
	private List<Map<String, Object>> getExportData(List<DataExportInfo> exportInfoList) {
		List<Map<String, Object>> dataMapList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(exportInfoList)) {
			exportInfoList.forEach(info -> {
				// 需要邮寄数据
				Map<String, Object> map = new HashMap<>();
				map.put("title", new ExportParams(info.getTitleName(), info.getSheetName()));
				map.put("entity", info.getEntity());
				map.put("data", info.getData() == null ? new ArrayList<>() : info.getData());
				dataMapList.add(map);
			});
		}
		return dataMapList;
	}
	@GetMapping("replace/replace")
	public String replace(){
		File file = new File("D:\\学习编程资料\\久其学习资料整理\\安徽一体化\\资产决算转存数据对比\\0330最新\\fa_data_v23.sql");
		try {
			InputStream inputStream=new FileInputStream(file);
			BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
			StringBuilder sb = new StringBuilder();
			String str;
			while (Objects.nonNull(str=bufferedReader.readLine())){
				sb.append(str+"\n");
			}
			List<FaDataMapping> faDataMapping=bookService.queryFADATAMAPPINGs();
			String chusstr= sb.toString();
			for (FaDataMapping dataMapping : faDataMapping) {
				String projectCode = "'"+dataMapping.getProjectCode()+"'";
				String projectCodeCzb = "'"+dataMapping.getProjectCodeCzb()+"'";
				chusstr=chusstr.replace(projectCode,projectCodeCzb);
			}
			dataWrite("D:\\学习编程资料\\久其学习资料整理\\安徽一体化\\资产决算转存数据对比\\0330最新\\fa_data_v232.sql",chusstr);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}


		return "成功！！！";
	}
	/**
	 * 写入数据
	 * @param filePath
	 * @param data
	 * @throws IOException
	 */
	public void dataWrite(String filePath, String data) throws IOException {
		File file = new File(filePath);
		if(file.exists()&&file.isFile()){
			java.io.FileWriter fileWriter = new FileWriter(file);
			fileWriter.write(data);
			fileWriter.flush();
			fileWriter.close();
		}
	}
	/**
	 * excel 生成sql工具
	 */
	@PostMapping("/upload/{name}")
	public String excelToSql(@PathVariable("name") String name,@RequestParam("file") MultipartFile files){
		try {
			InputStream inputStream = files.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}


}
